package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.annotation.OperationLog;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.department.DepartmentAddRequest;
import com.yupi.springbootinit.model.dto.department.DepartmentEditRequest;
import com.yupi.springbootinit.model.dto.department.DepartmentQueryRequest;
import com.yupi.springbootinit.model.dto.department.DepartmentUpdateRequest;
import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.DepartmentVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.DepartmentService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.Collections;
import java.util.List;

/**
 * 部门接口
 */
@RestController
@RequestMapping("/department")
@Slf4j
public class DepartmentController {

    @Resource
    private DepartmentService departmentService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 新增部门（仅管理员）
     *
     * @param departmentAddRequest 部门新增请求
     * @param request HTTP请求
     * @return 新部门ID
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "部门管理", operation = "新增", description = "管理员创建部门", recordParams = true, recordResult = true)
    public BaseResponse<Long> addDepartment(@RequestBody @Valid DepartmentAddRequest departmentAddRequest, HttpServletRequest request) {
        if (departmentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentAddRequest, department);
        departmentService.validDepartment(department, true);
        boolean result = departmentService.save(department);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建部门失败");
        }
        return ResultUtils.success(department.getId());
    }

    /**
     * 删除部门
     *
     * @param deleteRequest 删除请求
     * @param request HTTP请求
     * @return 受影响的用户列表
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "部门管理", operation = "删除", description = "管理员删除部门", recordParams = true, recordDataChange = true, recordResult = true)
    public BaseResponse<List<UserVO>> deleteDepartment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Department oldDepartment = departmentService.getById(id);
        if (oldDepartment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "部门不存在");
        }
        
        // 删除部门前，先将该部门中所有用户转移到"未分配"部门，并获取受影响的用户列表
        List<UserVO> affectedUsers = departmentService.transferUsersToUnassigned(id);
        
        // 删除部门
        boolean b = departmentService.removeById(id);
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除部门失败");
        }
        
        log.info("部门删除成功，部门ID: {}, 受影响用户数: {}", id, affectedUsers.size());
        
        return ResultUtils.success(affectedUsers);
    }

    /**
     * 更新部门（仅管理员）
     *
     * @param departmentUpdateRequest 部门更新请求
     * @return 更新结果
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @OperationLog(module = "部门管理", operation = "修改", description = "管理员更新部门信息", recordParams = true, recordDataChange = true, primaryKeyField = "id",recordResult = true)
    public BaseResponse<Boolean> updateDepartment(@RequestBody @Valid DepartmentUpdateRequest departmentUpdateRequest) {
        if (departmentUpdateRequest == null || departmentUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentUpdateRequest, department);
        // 参数校验
        departmentService.validDepartment(department, false);
        long id = departmentUpdateRequest.getId();
        // 判断是否存在
        Department oldDepartment = departmentService.getById(id);
        if (oldDepartment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "部门不存在");
        }
        boolean result = departmentService.updateById(department);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新部门失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取部门
     *
     * @param id 部门ID
     * @param request HTTP请求
     * @return 部门信息
     */
    @GetMapping("/get")
    public BaseResponse<DepartmentVO> getDepartmentById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = departmentService.getById(id);
        if (department == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(departmentService.getDepartmentVO(department));
    }

    /**
     * 分页获取部门列表（仅管理员）
     *
     * @param departmentQueryRequest 部门查询请求
     * @param request HTTP请求
     * @return 部门分页列表
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<DepartmentVO>> listDepartmentByPage(@RequestBody DepartmentQueryRequest departmentQueryRequest,
                                                                 HttpServletRequest request) {
        long current = departmentQueryRequest.getCurrent();
        long size = departmentQueryRequest.getPageSize();
        Page<Department> departmentPage = departmentService.page(new Page<>(current, size),
                departmentService.getQueryWrapper(departmentQueryRequest));
        Page<DepartmentVO> departmentVOPage = new Page<>(current, size, departmentPage.getTotal());
        List<DepartmentVO> departmentVO = departmentService.getDepartmentVO(departmentPage.getRecords());
        departmentVOPage.setRecords(departmentVO);
        return ResultUtils.success(departmentVOPage);
    }

    /**
     * 分页获取当前用户创建的部门列表
     *
     * @param departmentQueryRequest 部门查询请求
     * @param request HTTP请求
     * @return 当前用户创建的部门分页列表
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<DepartmentVO>> listMyDepartmentByPage(@RequestBody DepartmentQueryRequest departmentQueryRequest,
                                                                   HttpServletRequest request) {
        if (departmentQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long current = departmentQueryRequest.getCurrent();
        long size = departmentQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页大小不能超过20");
        }
        Page<Department> departmentPage = departmentService.page(new Page<>(current, size),
                departmentService.getQueryWrapper(departmentQueryRequest));
        Page<DepartmentVO> departmentVOPage = new Page<>(current, size, departmentPage.getTotal());
        List<DepartmentVO> departmentVO = departmentService.getDepartmentVO(departmentPage.getRecords());
        departmentVOPage.setRecords(departmentVO);
        return ResultUtils.success(departmentVOPage);
    }

    // endregion

    /**
     * 编辑部门（用户）
     *
     * @param departmentEditRequest 部门编辑请求
     * @param request HTTP请求
     * @return 编辑结果
     */
    @PostMapping("/edit")
    @OperationLog(module = "部门管理", operation = "编辑", description = "用户编辑部门信息", recordParams = true, recordDataChange = true, primaryKeyField = "id", recordResult = true)
    public BaseResponse<Boolean> editDepartment(@RequestBody @Valid DepartmentEditRequest departmentEditRequest, HttpServletRequest request) {
        if (departmentEditRequest == null || departmentEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentEditRequest, department);
        // 参数校验
        departmentService.validDepartment(department, false);
        long id = departmentEditRequest.getId();
        // 判断是否存在
        Department oldDepartment = departmentService.getById(id);
        if (oldDepartment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "部门不存在");
        }
        boolean result = departmentService.updateById(department);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "编辑部门失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取所有部门列表（用于下拉选择）
     *
     * @return 所有部门列表
     */
    @GetMapping("/list/all")
    public BaseResponse<List<DepartmentVO>> getAllDepartments(HttpServletRequest request) {
        User loginUser = userService.getLoginUserPermitNull(request);

        // 未登录或管理员：返回全部部门（保持原有行为）
        if (loginUser == null || userService.isAdmin(loginUser)) {
            List<DepartmentVO> departmentList = departmentService.getAllDepartments();
            return ResultUtils.success(departmentList);
        }

        // 部门负责人仅返回所在部门
        if (userService.isDeptLeader(loginUser)) {
            Long deptId = loginUser.getDepartmentId();
            if (deptId != null) {
                Department dept = departmentService.getById(deptId);
                if (dept != null) {
                    DepartmentVO vo = departmentService.getDepartmentVO(dept);
                    return ResultUtils.success(Collections.singletonList(vo));
                }
            }
            return ResultUtils.success(Collections.emptyList());
        }

        // 其他角色：保持原有行为（返回全部）
        List<DepartmentVO> departmentList = departmentService.getAllDepartments();
        return ResultUtils.success(departmentList);
    }

    /**
     * 根据部门ID获取用户列表
     *
     * - 管理员：可查看任意部门
     * - 部门负责人：仅可查看自己部门
     * - 其他角色：无权限
     *
     * @param departmentId 部门ID
     * @return 该部门的用户列表
     */
    @GetMapping("/users/{departmentId}")
    public BaseResponse<List<UserVO>> getUsersByDepartmentId(@PathVariable Long departmentId, HttpServletRequest request) {
        if (departmentId == null || departmentId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        // 管理员可查看任意部门
        if (userService.isAdmin(loginUser)) {
            List<UserVO> userList = departmentService.getUsersByDepartmentId(departmentId);
            return ResultUtils.success(userList);
        }

        // 部门负责人仅可查看自己部门
        if (userService.isDeptLeader(loginUser)
                && loginUser.getDepartmentId() != null
                && loginUser.getDepartmentId().equals(departmentId)) {
            List<UserVO> userList = departmentService.getUsersByDepartmentId(departmentId);
            return ResultUtils.success(userList);
        }

        throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该部门用户");
    }

    /**
     * 获取未分配部门的用户列表（仅管理员）
     *
     * @return 未分配部门的用户列表
     */
    @GetMapping("/users/unassigned")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<UserVO>> getUnassignedUsers() {
        // 获取或创建"未分配"部门
        Department unassignedDepartment = departmentService.getOrCreateUnassignedDepartment();
        List<UserVO> userList = departmentService.getUsersByDepartmentId(unassignedDepartment.getId());
        return ResultUtils.success(userList);
    }
}
